import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';

class MarqueeWidget extends StatefulWidget {
  final Duration duration;
  final double stepOffset;

  const MarqueeWidget({super.key, this.duration = const Duration(milliseconds: 500), this.stepOffset = 20});

  @override
  State<MarqueeWidget> createState() => _MarqueeWidgetState();
}

class _MarqueeWidgetState extends State<MarqueeWidget> {
  final tagAr = [
    "用户187****3344已提交受理",
    "用户158****3514已提交受理",
    "用户136****8456已提交受理",
    "用户198****1346已提交受理",
    "用户147****7890已提交受理",
    "用户191****1212已提交受理",
  ];

  List<String> avatar = ["a1.png", "a2.png", "a3.png", "a4.png", "a5.png", "a6.png"];

  late ScrollController controller;
  late Duration duration = widget.duration;
  late double stepOffset = widget.stepOffset;
  Timer? _timer;
  double _offset = 0.0;

  @override
  void initState() {
    super.initState();
    controller = ScrollController(initialScrollOffset: _offset);
    _timer = Timer.periodic(duration, (time) {
      double newOffset = controller.offset + stepOffset;
      if (newOffset != _offset) {
        _offset = newOffset;
        controller.animateTo(newOffset, duration: duration, curve: Curves.linear); // 线性曲线动画
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return IgnorePointer(
      child: ListView.separated(
        scrollDirection: Axis.horizontal,
        controller: controller,
        itemCount: 100000,
        // itemExtent: 16,
        itemBuilder: (context, index) {
          final i = Random().nextInt(tagAr.length);
          return Container(
            padding: const EdgeInsets.fromLTRB(3, 3, 14, 3),
            decoration: BoxDecoration(
              color: const Color(0XFFFEF6F2),
              borderRadius: BorderRadius.circular(16),
            ),
            child: Row(
              children: [
                ClipRRect(
                    borderRadius: BorderRadius.circular(24),
                    child: Image.asset(
                      "assets/avatars/${avatar[i]}",
                      width: 24,
                      height: 24,
                      errorBuilder: (context, obj, _) {
                        return Image.asset("assets/avatars/a4.png", width: 24, height: 24);
                      },
                    )),
                const SizedBox(width: 4),
                Text(
                  tagAr[i],
                  style: const TextStyle(fontSize: 13, color: Color(0XFF444444)),
                ),
              ],
            ),
          );
        },
        separatorBuilder: (BuildContext context, int index) {
          return const SizedBox(width: 8);
        },
      ),
    );
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }
}
